package com.media.appmedia.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

/**
 * 方法公用类
 */
public class MethodUtils {

	/**
	 * 文件大小数据转换为对应的字符串
	 * 
	 * @param fileSize
	 * @return
	 */
	public static String getFileSize2String(long fileSize) {
		String apkSizeStr = "0";
		double realSize = (double) (fileSize * 1.0 / (1024 * 1024 * 1.0));
		if (realSize > 1) {
			realSize = (double) (Math.round(realSize * 100) / 100.0);
			apkSizeStr = realSize + "M";
		} else {
			realSize = (double) (Math.round(realSize * 100000) / 100.0);
			apkSizeStr = realSize + "KB";
		}
		return apkSizeStr;
	}

	// private final static Pattern MOBILE_PATTERN = Pattern
	// .compile("(130|131|132|145|155|156|185|186|134|135|136|137|138|139|147|150|151|152|157|158|159|182|183|187|188|133|153|189|180|181|177)\\d{8}");

	public static boolean isMobile(String mobile) {
		if (mobile == null || mobile.length() != 11) {
			return false;
		}
		return true;
		// return MOBILE_PATTERN.matcher(mobile).matches();
	}

	/**
	 * 检查中文名输入是否正确
	 * 
	 * @param value
	 * @return
	 */
	public static boolean checkChineseName(String value, int length) {
		return value.matches("^[\u4e00-\u9fa5]+$") && value.length() <= length;
	}

	/** 验证邮箱是否合法 */
	public static boolean isEmailValid(String email) {
		boolean tag = true;
		Pattern pattern = Pattern
				.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");

		final Matcher mat = pattern.matcher(email);
		if (!mat.find()) {
			tag = false;
		}
		return tag;

	}

	/** 判断字符串是否为空 */
	public static boolean isEmpty(String str) {
		return str == null || str.length() == 0 || str.trim().length() == 0
				|| "null".equals(str.trim());
	}

	public static final int isBlankAny(String... str) {
		for (int i = 0; i < str.length; i++) {
			if (isEmpty(str[i])) {
				return i;
			}
		}
		return -1;
	}

	public static void saveUserInfo(Context context, String phone) {

	}

	public static void saveImageConfig(Context context, String path) {
		if (StringUtils.isEmpty(path))
			return;
		path = path + File.separator;
		SharedPreferences sp = context.getSharedPreferences(
				Const.SHAREPREFRENCE, Context.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putString(Const.IMG_DOWNLOAD_PATH, path);
		edit.commit();
	}

	// public static String getLargeImagePath(Context ctx) {
	// SharedPreferences sp = ctx.getSharedPreferences(Const.SHAREPREFRENCE,
	// Context.MODE_PRIVATE);
	// return sp.getString(Const.IMG_DOWNLOAD_PATH,
	// StorageUtil.getExternalStoragePath(ctx));
	// }

	public static String getLargeImagePath(Context ctx) {
		SharedPreferences sp = ctx.getSharedPreferences(Const.SHAREPREFRENCE,
				Context.MODE_PRIVATE);
		return sp.getString(Const.IMG_DOWNLOAD_PATH,
				StorageUtil.getLargeImagePath(ctx));
	}

	public static void saveAutoLoginConfig(Context context, boolean isAutoLogin) {
		SharedPreferences sp = context.getSharedPreferences(
				Const.SHAREPREFRENCE, Context.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putBoolean(Const.AUTO_LOGIN, isAutoLogin);
		edit.commit();
	}

	public static boolean getAutoLoginConfig(Context ctx) {
		SharedPreferences sp = ctx.getSharedPreferences(Const.SHAREPREFRENCE,
				Context.MODE_PRIVATE);
		return sp.getBoolean(Const.AUTO_LOGIN, true);
	}

	/**
	 * 更新配置文件
	 * 
	 * @param context
	 * @param key
	 * @param newdata
	 */
	public static void updateStringConfig(Context context, String key,
			String newdata) {
		SharedPreferences sp = context.getSharedPreferences(
				Const.SHAREPREFRENCE, Context.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putString(key, newdata);
		edit.commit();
	}

	public static void updateBooleanConfig(Context context, String key,
			boolean newdata) {
		SharedPreferences sp = context.getSharedPreferences(
				Const.SHAREPREFRENCE, Context.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putBoolean(key, newdata);
		edit.commit();
	}

	public static boolean getNoticeUpdateConfig(Context context) {
		SharedPreferences sp = context.getSharedPreferences(
				Const.SHAREPREFRENCE, Context.MODE_PRIVATE);
		return sp.getBoolean(Const.NOTICE_UPDATE, true);
	}

	public static String getStringConfig(Context context, String key) {
		SharedPreferences sp = context.getSharedPreferences(
				Const.SHAREPREFRENCE, Context.MODE_PRIVATE);
		return sp.getString(key, null);
	}

	/**
	 * 
	 * 方法说明：存储用户信息（电话）
	 * 
	 * @param context
	 * @return
	 */
	public static void setUserInfo(Context context, String phone) {
		SharedPreferences sp = context.getSharedPreferences(Const.UserInfoDown,
				Context.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putString("phone", phone);
		edit.commit();
	}

	/**
	 * 
	 * 方法说明：取出存储的手机信息
	 * 
	 * @param context
	 * @return
	 */
	public static String getUserInfo(Context context) {
		String userInfo = null;
		SharedPreferences sp = context.getSharedPreferences(Const.UserInfoDown,
				Context.MODE_PRIVATE);
		userInfo = sp.getString("phone", "");
		return userInfo;
	}

	/**
	 * 
	 * 方法说明：存储锁屏按钮的状态 默认为true
	 * 
	 * @param context
	 * @param tag
	 */
	public static void setSettingInfo1(Context context, boolean tag) {
		SharedPreferences sp = context.getSharedPreferences(
				Const.SettingInfoDown1, Context.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putBoolean("lock", tag);
		edit.commit();
	}

	/**
	 * 
	 * 方法说明：取出本地化存储的设置---是否开启锁屏，默认为true
	 * 
	 * @param context
	 * @return
	 */
	public static boolean getSetting1(Context context) {
		boolean setting;
		SharedPreferences sp = context.getSharedPreferences(
				Const.SettingInfoDown1, Context.MODE_PRIVATE);
		setting = sp.getBoolean("lock", true);
		return setting;
	}

	/**
	 * 
	 * 方法说明：存储本地设置 通知栏的开启状态，默认为false
	 * 
	 * @param context
	 * @param tag
	 */
	public static void setSettingInfo2(Context context, boolean tag) {
		SharedPreferences sp = context.getSharedPreferences(
				Const.SettingInfoDown2, Context.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putBoolean("notification", tag);
		edit.commit();
	}

	/**
	 * 
	 * 方法说明：取出本地化存储的设置--是否开启通知栏提醒，默认false
	 * 
	 * @param context
	 * @return
	 */
	public static boolean getSetting2(Context context) {
		boolean setting;
		SharedPreferences sp = context.getSharedPreferences(
				Const.SettingInfoDown2, Context.MODE_PRIVATE);
		setting = sp.getBoolean("notification", false);
		return setting;
	}

	/**
	 * 
	 * 方法说明：设置界面用户设置本地化存储
	 * 
	 * @param context
	 * @param tag
	 */
	public static void setSettingInfo3(Context context, boolean tag) {
		SharedPreferences sp = context.getSharedPreferences(
				Const.SettingInfoDown3, Context.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putBoolean("sound", tag);
		edit.commit();
	}

	public static boolean getSetting3(Context context) {
		boolean setting;
		SharedPreferences sp = context.getSharedPreferences(
				Const.SettingInfoDown3, Context.MODE_PRIVATE);
		setting = sp.getBoolean("sound", false);
		return setting;
	}

	/**
	 * 
	 * 方法说明：存储当前锁屏数据版本
	 * 
	 * @param context
	 * @param tag
	 */
	public static void setLockInfo(Context context, int tag) {
		SharedPreferences sp = context.getSharedPreferences(Const.LOCK_INFO,
				Context.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putInt("lock", tag);
		edit.commit();
	}

	public static int getLockInfo(Context context) {
		int lock;
		SharedPreferences sp = context.getSharedPreferences(Const.LOCK_INFO,
				Context.MODE_PRIVATE);
		lock = sp.getInt("lock", 0);
		return lock;
	}

	/**
	 * 
	 * 方法说明：存储是否有新消息
	 * 
	 * @param context
	 * @param tag
	 */
	public static void setMessge(Context context, int tag) {
		SharedPreferences sp = context.getSharedPreferences(Const.MESSGE,
				Context.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putInt("messge", tag);
		edit.commit();
	}

	public static int getMessge(Context context) {
		int lock;
		SharedPreferences sp = context.getSharedPreferences(Const.MESSGE,
				Context.MODE_PRIVATE);
		lock = sp.getInt("messge", 0);
		return lock;
	}

	/**
	 * 
	 * 方法说明：存储是否需要弹出
	 * 
	 * @param context
	 * @param tag
	 */
	public static void setShare(Context context, int tag) {
		SharedPreferences sp = context.getSharedPreferences(Const.SHARE,
				Context.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putInt("share", tag);
		edit.commit();
	}

	public static int getShare(Context context) {
		int share;
		SharedPreferences sp = context.getSharedPreferences(Const.SHARE,
				Context.MODE_PRIVATE);
		share = sp.getInt("share", 0);
		return share;
	}

	/**
	 * 格式化时间的
	 */
	/*
	 * public static String formatTime(Context ctx, long nowTime, long preTime)
	 * { Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH,
	 * cal.get(Calendar.DAY_OF_MONTH) - 1); cal.set(Calendar.HOUR_OF_DAY, 0);
	 * cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0);
	 * cal.set(Calendar.MILLISECOND, 0); long time = nowTime - preTime; long
	 * second = time / 1000; if (second < 60) { return
	 * ctx.getResources().getString(R.string.just); } else if (second >= 60 &&
	 * second < 3600) { return second / 60 +
	 * ctx.getResources().getString(R.string.minute_ago); } else if (second >=
	 * 3600 && second < 3600 * 24) { return second / 3600 +
	 * ctx.getResources().getString(R.string.hour_ago); } else if (second >=
	 * 3600 * 24 && second < (nowTime - cal.getTimeInMillis()) / 1000) { return
	 * ctx.getResources().getString(R.string.yesterday); } else if (second >=
	 * 3600 * 24 && second < 3600 * 24 * 2) { return
	 * ctx.getResources().getString(R.string.yesterday); } else {
	 * cal.setTimeInMillis(preTime); return DateUtils.getDate(preTime); //
	 * return cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + // 1) //
	 * + "-" + cal.get(Calendar.DAY_OF_MONTH); } }
	 */
	/**
	 * 格式化时间的 转换为距当前时间以后
	 */
	/*
	 * public static String formatTimeAfter(Context ctx, long afterTime, long
	 * nowTime) { Calendar cal = Calendar.getInstance();
	 * cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) - 1);
	 * cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.SECOND, 0);
	 * cal.set(Calendar.MINUTE, 0); cal.set(Calendar.MILLISECOND, 0); long time
	 * = afterTime - nowTime; long second = time / 1000; if (second < 60) {
	 * return second + ctx.getResources().getString(R.string.second); } else if
	 * (second >= 60 && second < 3600) { return second / 60 +
	 * ctx.getResources().getString(R.string.minute); } else if (second >= 3600
	 * && second < 3600 * 24) { return second / 3600 +
	 * ctx.getResources().getString(R.string.hour); } else if (second >= 3600 *
	 * 24 && second < 3600 * 24 * 2) { return second / (3600 * 24) +
	 * ctx.getResources().getString(R.string.day); } else {
	 * cal.setTimeInMillis(afterTime); return DateUtils.getDate(afterTime); //
	 * return cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + // 1) //
	 * + "-" + cal.get(Calendar.DAY_OF_MONTH); } }
	 */
	public static InputFilter getInputLenFilter(final Context context,
			final int len) {
		return new InputFilter() {

			@Override
			public CharSequence filter(CharSequence source, int start, int end,
					Spanned dest, int dstart, int dend) {
				try {
					// 转换成中文字符集的长度
					int destLen = dest.toString().getBytes("GB18030").length;
					int sourceLen = source.toString().getBytes("GB18030").length;
					// 如果超过34个字符
					while (destLen + sourceLen > len) {
						source = source.subSequence(0, source.length() - 1);
						sourceLen = source.toString().getBytes("GB18030").length;
					}
					// 如果按回退键
					// if (source.length() < 1 && (dend - dstart >= 1)) {
					// return dest.subSequence(dstart, dend - 1);
					// }
					// 其他情况直接返回输入的内容
					return source;

				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return "";
			}
		};
	}

	/**
	 * 隐藏软件盘
	 * 
	 * @param context
	 * @param view
	 */
	public static void hideInputKeyBorad(Context context, EditText view) {
		InputMethodManager inputMethodManager = (InputMethodManager) context
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS); // 隐藏
	}

	/**
	 * 弹出软键盘
	 * 
	 * @param context
	 * @param view
	 */
	public static void showSoftKeyboard(Context context, EditText view) {
		InputMethodManager imm = (InputMethodManager) context
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
	}

	private static long preBackTime; // 记录上次按back键的时间

	/*
	 * public static boolean canExit(Context ctx) { if
	 * (System.currentTimeMillis() - preBackTime < 1500) { preBackTime = 0;
	 * return true; } preBackTime = System.currentTimeMillis();
	 * ToastUtils.show(ctx, R.string.exit_app_msg); return false; }
	 * 
	 * public static void exit(Activity ctx) {
	 * UserFeedBackTool.feedBackDelay(UserFeedbackAction.ACTION_END, null);
	 * UserFeedBackTool.flushFeedBack();
	 * ImageLoader.getInstance().clearMemoryCache();
	 * CacheFileMgr.getInstance().gc(); UploadTaskMgr.getInstance().gc();
	 * DownloadTaskMgr.getInstance().gc(); DBMgr.getInstance().closeDB();
	 * UserMgr.getInstance().gc(); UpdateClientMgr.getInstance(ctx).gc();
	 * DownloadTool.stopService(ctx); UploadTool.stopService(ctx); }
	 */
	/**
	 *  Rose
	 * 方法说明：时间戳--即秒数，将之乘1000转化为毫秒数即可解开
	 * 
	 * @param times
	 *            秒数
	 * @return
	 */
	public static String getTimer(String times) {
		String time = null;
		Date date = new Date(Long.parseLong(times) * 1000L);
		SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		time = sdf.format(date);
		return time;
	}
	/**
	 *  Rose
	 * 方法说明：时间戳--即秒数，将之乘1000转化为毫秒数即可解开
	 * 
	 * @param times
	 *            秒数
	 * @return
	 */
	public static String getTimers(String times) {
		String time = null;
		Date date = new Date(Long.parseLong(times) * 1000L);
		SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		time = sdf.format(date);
		return time;
	}

}
